package test

import (
	"database/sql"
	"encoding/json"
	"github.com/gin-gonic/gin"
	_ "github.com/go-sql-driver/mysql"
)

// StaffAuth 用于映射数据库中的数据
type StaffAuth struct {
	CityID    string `db:"city_id"`
	ProjectID string `db:"project_id"`
	StaffID   int    `db:"staff_id"`
	StaffName string `db:"staff_name"`
	Type      int    `db:"type"`
}

// AuthList 用于构建最终的JSON格式
type AuthList struct {
	CityID string `json:"city_id"`
	Auth   []struct {
		ProjectID string `json:"project_id"`
		Type      int    `json:"type"`
	} `json:"auth"`
}

// DataResponse 最终的JSON响应格式
type DataResponse struct {
	Data []struct {
		StaffName string     `json:"staff_name"`
		AuthList  []AuthList `json:"auth_list"`
	} `json:"data"`
}

func getStaffAuth(db *sql.DB) ([]StaffAuth, error) {
	rows, err := db.Query("SELECT city_id, project_id, staff_id, staff_name, type FROM manager")
	if err != nil {
		return nil, err
	}
	defer rows.Close()

	var staffAuths []StaffAuth
	for rows.Next() {
		var sa StaffAuth
		err := rows.Scan(&sa.CityID, &sa.ProjectID, &sa.StaffID, &sa.StaffName, &sa.Type)
		if err != nil {
			return nil, err
		}
		staffAuths = append(staffAuths, sa)
	}

	return staffAuths, nil
}

func processData(staffAuths []StaffAuth) DataResponse {
	authMap := make(map[string][]StaffAuth)

	for _, sa := range staffAuths {
		authMap[sa.StaffName] = append(authMap[sa.StaffName], sa)
	}

	var dataResponse DataResponse
	for staffName, auths := range authMap {
		var authLists []AuthList
		cityAuths := make(map[string][]struct {
			ProjectID string `json:"project_id"`
			Type      int    `json:"type"`
		})

		for _, auth := range auths {
			cityAuths[auth.CityID] = append(cityAuths[auth.CityID], struct {
				ProjectID string `json:"project_id"`
				Type      int    `json:"type"`
			}{ProjectID: auth.ProjectID, Type: auth.Type})
		}

		for cityID, auths := range cityAuths {
			authLists = append(authLists, AuthList{CityID: cityID, Auth: auths})
		}

		dataResponse.Data = append(dataResponse.Data, struct {
			StaffName string     `json:"staff_name"`
			AuthList  []AuthList `json:"auth_list"`
		}{StaffName: staffName, AuthList: authLists})
	}

	return dataResponse
}

func main() {
	router := gin.Default()

	router.GET("/staff-auth", func(c *gin.Context) {
		db, err := sql.Open("mysql", "root:123456@tcp(127.0.0.1:3306)/blog")
		if err != nil {
			c.JSON(500, gin.H{"error": err.Error()})
			return
		}
		defer db.Close()

		staffAuths, err := getStaffAuth(db)
		if err != nil {
			c.JSON(500, gin.H{"error": err.Error()})
			return
		}

		dataResponse := processData(staffAuths)
		jsonData, err := json.Marshal(dataResponse)
		if err != nil {
			c.JSON(500, gin.H{"error": err.Error()})
			return
		}

		c.Data(200, "application/json", jsonData)
	})

	router.Run(":8080")
}
